package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"weiyun-management-system/models/cache"
	"weiyun-management-system/models/mysql"
	"weiyun-management-system/pkg"

	"weiyun-management-system/weirpc/internal/svc"
	"weiyun-management-system/weirpc/weirpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *weirpc.LoginRequest) (*weirpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	result, _ := cache.Rdb.Get(cache.Ctx, "captcha"+in.Mobile).Result()
	if result != in.CaptchaCode {
		return nil, errors.New("图形验证码错误，请重新输入")
	}
	s, _ := cache.Rdb.Get(cache.Ctx, "sendSms"+in.Mobile).Result()
	if s != in.SmsCode {
		return nil, errors.New("短信验证码错误，请重新输入")
	}

	user := &mysql.User{
		Mobile:    in.Mobile,
		Password:  pkg.Md5(in.Password),
		HeadImage: "https://hbimg.huabanimg.com/50271a224511944d63977f8f68d3f00c021ebe3c6768-NSqY16_fw658",
		NickName:  fmt.Sprintf("用户_%d", rand.Intn(10000)),
	}
	err := user.UserFistOrcreate(mysql.DB, in.Mobile)
	if err != nil {
		return nil, err

	}
	if user.Password != pkg.Md5(in.Password) {
		return nil, errors.New("密码错误，请重新输入")
	}

	Login := &mysql.UserLogin{

		Mobile: in.Mobile,
		Ip:     pkg.GetOutboundIP(),
	}
	err = Login.UserLoginCreate(mysql.DB)
	if err != nil {
		logx.Error(err)
	}
	cache.Rdb.Del(cache.Ctx, "sendSms"+user.Mobile)
	cache.Rdb.Del(cache.Ctx, "captcha"+in.Mobile)
	return &weirpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
